package org.zebra.beansearch;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.zhxu.bs.util.MapBuilder;
import cn.zhxu.bs.util.MapUtils;
import org.zebra.common.core.PageQuery;

/**
 * @author zhanghongbin
 */
public class BPageQuery extends PageQuery<MapBuilder> {

    @Override
    public MapBuilder build() {
        Integer pageNum = ObjectUtil.defaultIfNull(this.getPage(), DEFAULT_PAGE_NUM);
        Integer pageSize = ObjectUtil.defaultIfNull(this.getSize(), DEFAULT_PAGE_SIZE);
        if (pageNum <= 0) {
            pageNum = DEFAULT_PAGE_NUM;
        }
        MapBuilder mapBuilder = MapUtils.builder().page(pageNum, pageSize);
        return this.buildSortOrder(mapBuilder);
    }

    /**
     * 构建排序
     * <p>
     * 支持的用法如下:
     * {order:"asc",sort:"id"} order by id asc
     * {order:"asc",sort:"id,createTime"} order by id asc,create_time asc
     * {order:"desc",sort:"id,createTime"} order by id desc,create_time desc
     * {order:"asc,desc",sort:"id,createTime"} order by id asc,create_time desc
     */
    private MapBuilder buildSortOrder(MapBuilder mapBuilder) {
        if (CharSequenceUtil.isEmpty(this.getSort()) || CharSequenceUtil.isEmpty(this.getOrder())) {
            return mapBuilder;
        }
        String[] sortByArr = this.getSort().split(",");
        String[] orderByArr = this.getOrder().split(",");
        if (sortByArr.length != 1 && sortByArr.length != orderByArr.length) {
            return mapBuilder;
        }
        // 每个字段各自排序
        for (int i = 0; i < sortByArr.length; i++) {
            String sortByStr = sortByArr[i];
            String orderByStr = orderByArr.length == 1 ? orderByArr[0] : orderByArr[i];
            if ("asc".equals(orderByStr)) {
                mapBuilder.orderBy(sortByStr, "asc");
            } else if ("desc".equals(orderByStr)) {
                mapBuilder.orderBy(sortByStr, "desc");
            } else {
                return mapBuilder;
            }
        }
        return mapBuilder;
    }
}
